package com.cy.store.service.impl;

import com.cy.store.entity.User;
import com.cy.store.mapper.UserMapper;
import com.cy.store.service.IUserService;
import com.cy.store.service.ex.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.Objects;
import java.util.UUID;

/**
 * @author: AngJie
 * @create: 2022-02-06 00:09
 **/
// @Service将当前类的对象交给Spring来管理，自动创建对象以及对象的维护
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public void regist(User user) {
        //通过user参数获取传递过来的username
        String username = user.getUsername();
        // 调用findByUsername(username) 判断用户是否被注册过
        if ((userMapper.findByUsername(username) != null)) {
            //抛出异常
            throw new UsernameDuplicatedException("用户名被占用");
        }

        // 密码加密处理的实现：md5算法
        // 串 + password + 串 ---md5算法进行加密,；连续加载三次
        // 盐值 + password + 盐值 --- 盐值就是一个随机的字符串
        String oldPassword = user.getPassword();
        //获取盐值(随机生成)
        String salt = UUID.randomUUID().toString().toUpperCase();
        //补全数据:盐值的记录,用于登录验证
        user.setSalt(salt);
        //将密码和盐值作为一个整体进行加密处理,忽略原有密码强度提升了数据的安全性
        String md5Password = getMD5Password(oldPassword, salt);
        //将加密之后的密码重新补全到user对象中
        user.setPassword(md5Password);
        // 补全数据: is_delete设置为0
        user.setIsDelete(0);
        //补全数据:4个日志字段信息
        user.setCreatedUser(user.getUsername());
        Date date = new Date();
        user.setCreatedTime(date);
        user.setModifiedUser(user.getUsername());
        user.setModifiedTime(date);

        // 执行注册业务功能的实现
        Integer rows = userMapper.insert(user);
        if (rows != 1) {
            throw new InsertException("在用户注册过程中产生了未知的异常");
        }
    }

    @Override
    public User login(User user) {
        //根据用户名称来查询用户的数据是否存在，不在则抛出异常
        User result = userMapper.findByUsername(user.getUsername());
        if (result == null) {
            throw new UserNotFonudException("用户数据不存在");
        }
        if (result.getIsDelete() == 1) {
            throw new LoggedOffException("该用户已经注销");
        }

        //检测用户的密码是否匹配
        //1. 先获取到数据库中加密的密码
        String password = result.getPassword();
        //2. 和用户传递过来的密码进行比较
        //2.1 先获取盐值，注册时进行了保存
        String salt = result.getSalt();
        //2.2 将用户的密码按照相同规则进行加密
        String md5Password = getMD5Password(user.getPassword(), salt);
        //3 将密码进行比较
        if (!Objects.equals(md5Password, password)) {
            throw new PasswordNotMatchException("用户密码错误!");
        }

        // 减少数据量的体量,提升系统的性能
        User user1 = new User();
        user1.setUsername(result.getUsername());
        user1.setAvatar(result.getAvatar());
        user1.setUid(result.getUid());

        // 将当前用户数据返回，返回的数据是为了辅助其他页面做数据展示使用(uid,username,avatar)
        return user1;

    }

    /**
     * 修改密码
     *
     * @param uid
     * @param oldPassword
     * @param newPassword
     */
    @Override
    public void changePassword(Integer uid, String oldPassword, String newPassword) {
        User result = userMapper.findByUid(uid);
        // 已经查到了用户数据 可以减少一个username参数
        String username = result.getUsername();
        if (result == null) {
            throw new UserNotFonudException("用户未找到");
        }
        if (result.getIsDelete() == 1) {
            throw new LoggedOffException("用户已经注销");
        }
        //原始密码和数据库中密码进行比较
        String oldMd5Password = getMD5Password(oldPassword, result.getSalt());
        if (!Objects.equals(result.getPassword(), oldMd5Password)) {
            throw new PasswordNotMatchException("原始密码输入错误");
        }
        String newMd5Password = getMD5Password(newPassword, result.getSalt());
        if (Objects.equals(newMd5Password, result.getPassword())) {
            throw new PasswordDuplicatedException("新密码不能与旧密码相同");
        }
        // 将加密后的新密码设置进去
        Integer rows = userMapper.updatePasswordByUid(uid, newMd5Password, new Date(), username);
        if (rows != 1) {
            throw new UpdateException("更新数据时产生未知异常");
        }
    }

    /**
     * 根据用户的id查询用户数据
     *
     * @param uid
     * @return 根据uid查到的用户数据
     */
    public User getByUid(Integer uid) {
        User result = userMapper.findByUid(uid);
        if (result == null) {
            throw new UserNotFonudException("用户未找到");
        }
        if (result.getIsDelete() == 1) {
            throw new LoggedOffException("用户已经注销");
        }
        return result;
    }


    /**
     * 更新用户数据
     *
     * @param uid
     * @param user
     */
    @Override
    public void changeInfo(Integer uid, User user) {
        User result = userMapper.findByUid(uid);
        if (result == null) {
            throw new UserNotFonudException("用户未找到");
        }
        if (result.getIsDelete() == 1) {
            throw new LoggedOffException("用户已经注销");
        }
        user.setUid(uid);
        // 已经查到了用户数据 可以减少一个username参数
        user.setModifiedUser(result.getUsername());
        user.setModifiedTime(new Date());

        Integer rows = userMapper.updateInfo(user);
        if (rows != 1) {
            throw new UpdateException("更新数据时产生位置的异常");
        }
    }

    @Override
    public void changeAvatar(Integer uid, String avatar) {
        // 查询当前的用户数据是否存在
        User result = userMapper.findByUid(uid);
        if (result == null) {
            throw new UserNotFonudException("用户未找到");
        }
        if (result.getIsDelete() == 1) {
            throw new LoggedOffException("用户已经注销");
        }
        Integer rows = userMapper.updateAuatarByUid(uid, avatar, result.getUsername(), new Date());
        if (rows != 1){
            throw new UpdateException("更新头像时发生了未知异常");
        }
    }

    /**
     * @param password
     * @param salt
     * @return md5三次加密后的密码
     * @author AngJie
     * @creed: Talk is cheap,show me the code
     * @date 2022/2/6 0006 0:37
     */
    private String getMD5Password(String password, String salt) {
        // md5加密算法的调用(3次加密)
        for (int i = 0; i < 3; i++) {
            password = DigestUtils.md5DigestAsHex((salt + password + salt).getBytes());
        }

        //返回加密之后的密码
        return password;
    }


}